package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.node.NodeType
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.NodeSelection

class InsertCmd(val mathNodeType: NodeType,
                val initialText:String = ""
): Command{
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?
    ): Boolean {
        val from = state.selection._from
        val index = from.index()
        if (!from.parent.canReplaceWith(index, index, mathNodeType)) {
            return false
        }
        if (dispatch!=null){
            val node = if(initialText.isNotEmpty()) state.schema.text(initialText) else null
            val mathNode = mathNodeType.create(null, node)
            var tr = state.tr.replaceSelectionWith(mathNode)
            tr = tr.setSelection(NodeSelection.create(tr.doc, from.pos))
            dispatch(tr)
        }
        return true;
    }
}

fun Command.Companion.insert(mathNodeType: NodeType,
                             initialText:String = "") = InsertCmd(mathNodeType,initialText)